package com.tdf.lolpanel.service.impl;

import com.tdf.lolpanel.constant.JwtConstant;
import com.tdf.lolpanel.constant.MsgConstant;
import com.tdf.lolpanel.constant.StatusConstant;
import com.tdf.lolpanel.context.BaseContext;
import com.tdf.lolpanel.dto.RoomRegisterDTO;
import com.tdf.lolpanel.entity.Room;
import com.tdf.lolpanel.mapper.RoomMapper;
import com.tdf.lolpanel.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class RoomServiceImpl implements RoomService {

    @Autowired
    private RoomMapper roomMapper;


    /**
     * 查询房间
     */
    public Room get(Integer id) {
        Room room = roomMapper.getById(id);

        if (room == null) {
            // 房间不存在
            throw new IllegalStateException(MsgConstant.ROOM_NOT_FOUND);
        }

        return room;
    }

    /**
     * 添加房间
     */
    @Override
    public void add(RoomRegisterDTO roomRegisterDTO) {
        String uId = BaseContext.get(JwtConstant.UID);
        String uSta = BaseContext.get(JwtConstant.STATUS);

        // 处理异常情况
        if (uId == null) {
            // 无用户，即未登录
            throw new IllegalStateException(MsgConstant.USER_NOT_LOGIN);
        }
        else if (Integer.valueOf(uSta).equals(StatusConstant.USR_DISABLE)) {
            // 账号禁用
            throw new IllegalStateException(MsgConstant.ACCOUNT_LOCKED);
        } else if (roomRegisterDTO.getName() == null) {
            // 名称无效
            throw new IllegalStateException(MsgConstant.ROOM_INVALID_NAME);
        }

        Room room = new Room();

        // 对象属性拷贝
        room.setName(roomRegisterDTO.getName());
        room.setOwnerId(uId);

        // 设置其他参数
        room.setStatus(StatusConstant.ROOM_ENABLE);

        // 设置记录时间和修改时间
        room.setCreatedTime(LocalDateTime.now());
        room.setUpdatedTime(LocalDateTime.now());

        // 数据库操作
        roomMapper.insert(room);
    }

}
